﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net;
using HtmlAgilityPack;
using StockFinder.Model;
using StockFinder.Network;

namespace StockFinder.ExchangeLists.FTSE
{
    public class YahooFinanceFtse250StockIndexList : IStockIndexList
    {
        readonly string[] URLS = new string[]
        {
            "http://uk.finance.yahoo.com/q/cp?s=%5EFTMC",
            "http://uk.finance.yahoo.com/q/cp?s=%5EFTMC&c=1",
            "http://uk.finance.yahoo.com/q/cp?s=%5EFTMC&c=2",
            "http://uk.finance.yahoo.com/q/cp?s=%5EFTMC&c=3",
            "http://uk.finance.yahoo.com/q/cp?s=%5EFTMC&c=4",
            "http://uk.finance.yahoo.com/q/cp?s=%5EFTMC&c=5"
        };

        public List<Symbol> GetStockIndexList()
        {
            var stockIndexList = new List<Symbol>();

            foreach (var url in URLS)
            {
                using (ProxiedWebClient webClient = new ProxiedWebClient())
                {
                    string pageSource = webClient.DownloadString(url);

                    HtmlDocument doc = new HtmlDocument();
                    doc.LoadHtml(pageSource);

                    List<string> hrefTags = new List<string>();

                    foreach (HtmlNode link in doc.DocumentNode.SelectNodes("//a[@href]"))
                    {
                        HtmlAttribute att = link.Attributes["href"];
                        hrefTags.Add(att.Value);

                        if (att.Value.Contains("/q?s=") && !att.Value.Contains("%"))
                        {
                            var ticker = att.Value.Replace("/q?s=", string.Empty);
                            if (ticker.EndsWith(".L"))
                            {
                                ticker = ticker.Substring(0, ticker.Length - 2);
                            }
                            stockIndexList.Add(new Symbol() { Name = ticker, Exchange = Model.Enumerations.Exchange.LONDON });                            
                        }
                    }
                }   
            }

            return stockIndexList;
        }

        public string Name
        {
            get { return "FTSE 250"; }
        }

        public override string ToString()
        {
            return Name;
        }
    }
}
